#include "stdafx.h"

#include "SocketServer.h"
#include "PacketAnalyzer.h"
#include "PacketCollector.h"
#include "TradeAgentClientDLL.h"
#include <stdio.h>

static char* ipAddressString = "127.0.0.1";
static int port = 9000;

#define D_SEND_BUFFER_LENGTH 4096 * 1000
#define D_RCV_BUFFER_LENGTH 4096 * 1000
static char gRcvBuffer[D_SOCKET_CONN_MAX][D_RCV_BUFFER_LENGTH];
static PacketAnalyzController gPacketCtrl[D_SOCKET_CONN_MAX];
static int gRcvLength;
static SocketConnectionHandle gSocketHandle;



static void onConn(SubConnectionHandle h)
{
	int rcvCount = 0;
	int conn_no = SubConn_GetNo(h);
	char *pRcvBuf = gRcvBuffer[conn_no];
	int rcvBufLen = D_RCV_BUFFER_LENGTH;

	char *pSndBuf = NULL;
	int sndLen = 0;

	PacketAnalyzController *pPackCtrl = &gPacketCtrl[conn_no];
	Packet packet;
	PacketReaderHandle readerHandle;
	PacketWriterHandle writerHandle;
	int ret;

	PacketAnalyzerInit(pPackCtrl);


	while (true)
	{
		rcvBufLen = D_RCV_BUFFER_LENGTH;
		rcvCount = SubConn_RcvData(h, pRcvBuf, &rcvBufLen);
		if (rcvCount <= 0)
			break;
		// printf("Get data,len=%d.\r\n", rcvBufLen);
		ret = PacketAnalyzerAddData(pPackCtrl, pRcvBuf, rcvBufLen, &packet);
		if (ret == 0)
		{
			// printf("Packet get continue.\r\n");
			continue;
		}

		// Get packet
		printf("Get one packet!.\r\n");
		readerHandle = PacketReaderCreate(packet);

		ret = ReceivePacketSet(readerHandle);


		ret = SendPacketGet(&writerHandle);
		printf("Send packet.\r\n");
		PacketWriterGetPacket(writerHandle, &packet);
		PacketAnalyzerSetHeader(&packet, &pSndBuf, &sndLen);
		ret = SubConn_SendData(h, pSndBuf, sndLen);
		SendPacketFree();
		printf("Send packet finish.\r\n");

	}
	SendPacketFree();

}


void PipeInit()
{
	printf("Init Connection Server.ip=%s:%d\n", ipAddressString, port);
	gSocketHandle = SocketServer_Create();
	PacketCollectInit();
	SocketServer_Connect(gSocketHandle, ipAddressString, port, onConn);

	return;
}
void PipeClose()
{
	printf("CloseConnection \n");
	SocketServer_Close(&gSocketHandle);
	return;
}

int PipeGetPacket(PacketReaderHandle *handle)
{
	return ReceivePacketGet(handle);
}

int PipeSendPacket(PacketWriterHandle handle)
{
	return SendPacketSet(handle);
}
